package top.yzhelp.enjoyinformation.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import top.yzhelp.enjoyinformation.controller.res.CodeMsg;
import top.yzhelp.enjoyinformation.controller.res.Result;
import top.yzhelp.enjoyinformation.model.User;
import top.yzhelp.enjoyinformation.service.UserService;
import top.yzhelp.enjoyinformation.shiro.ShiroRealm;
import top.yzhelp.enjoyinformation.wx.util.JwtUtil;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Map;

/**
 * @author 码之泪殇 GitHub: https://github.com/gongsir0630
 * @date 2021/3/19 17:42
 * 你的指尖,拥有改变世界的力量
 * @description 用户接口
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private JwtUtil jwtUtil;

    /**
     * 从认证信息中获取用户Id: userId == openId
     * @return userId
     */
    private String getUserId() {
        return ShiroRealm.getUserId();
    }

    /**
     * 小程序用户登录
     * @description 小程序用户登录接口: 通过js_code换取openId, 判断用户是否已经注册
     * @param code wx.login() 得到的code凭证
     * @return token
     */
    @PostMapping("/login")
    public ResponseEntity<Result<LoginResult>> login(String code) {
        if (StringUtils.isBlank(code)) {
            return new ResponseEntity<>(Result.fail(new CodeMsg(401,"code is empty"), null),HttpStatus.OK);
        }
        log.info("--->接收到来自小程序端的code:[{}]",code);
        // todo: 使用 code -> wxAccountService.login() -> openId,session_key
        Map<String, String> loginMap = userService.login(code);
        boolean canLogin = Boolean.parseBoolean(loginMap.get("canLogin"));
        String token = loginMap.get("token");
        LoginResult data = new LoginResult();
        data.setToken(token);
        data.setCanLogin(canLogin);
        log.info("--->>>返回认证信息:[{}]", data.toString());
        if (!canLogin) {
            // todo: 用户不存在,提示用户注册
            return new ResponseEntity<>(Result.fail(CodeMsg.NO_USER,data),HttpStatus.OK);
        }
        String openId = loginMap.get("openId");
        data.setUser(this.userService.getById(openId));
        return new ResponseEntity<>(Result.success(data),HttpStatus.OK);
    }

    /**
     * 用户注册/更新个人信息
     * @param user 用户信息
     * @return success
     */
    @PostMapping("")
    @RequiresAuthentication
    public ResponseEntity<Result<JSONObject>> updateUserInfo(User user) {
        user.setUserId(getUserId());
        userService.saveOrUpdate(user);
        return new ResponseEntity<>(Result.success(null),HttpStatus.OK);
    }
}
@Data
class LoginResult implements Serializable {
    /**
     * token签名
     */
    private String token;
    /**
     * 登录状态
     */
    private boolean canLogin;
    /**
     * 用户信息
     */
    private User user;
}